Popular Searches
Popular Course Categories
Popular Courses

Modify Web Elements

JavaScript with Selenium

Modify Web Elements in Selenium WebDriver

Modifying Web Elements in Selenium WebDriver means changing, updating, inspecting, or controlling the properties, attributes, values, styles, text, or state of HTML elements during automated testing. Selenium provides the WebElement interface for normal interaction with elements, while JavaScriptExecutor can be used when direct DOM-level modification is required.

Web Element modification is useful when working with dynamic web applications, debugging automation scripts, changing test data in controlled environments, inspecting element properties, modifying CSS for debugging, working with hidden or disabled states during specialized testing, and validating how the DOM behaves after a change.

Selenium WebDriver training commonly covers locating elements, WebDriver commands, forms, buttons, dropdowns, navigation, and working with WebElements as part of browser automation.

Selenium Training Course | Register for Course Demo


1. What is a Web Element?

A Web Element is an HTML element displayed or represented in the browser DOM. Examples include text fields, buttons, links, checkboxes, radio buttons, dropdowns, images, labels, tables, forms, and containers.

<input id="username" type="text" name="username">

<button id="login">Login</button>

<a href="/home">Home</a>

2. What Does Modify Web Elements Mean?

Modify Web Elements means changing some part of an existing HTML element or its current DOM state during test execution.

  • Change an input value
  • Change an HTML attribute
  • Add or remove a CSS class
  • Change CSS properties
  • Change element text
  • Change visibility
  • Change checkbox or radio state
  • Add or remove attributes
  • Modify image properties
  • Modify links
  • Modify form controls
  • Highlight elements for debugging

3. Why Modify Web Elements?

Element modification is useful in specialized automation and debugging scenarios. It can help testers inspect the DOM, prepare controlled test states, visualize elements, and investigate application behavior.

  • Debug difficult UI problems
  • Inspect dynamic elements
  • Highlight elements
  • Modify test data
  • Change temporary CSS
  • Test specific DOM states
  • Inspect attributes
  • Investigate hidden elements
  • Validate dynamic application behavior

4. Selenium WebElement and JavaScriptExecutor

TechniquePurposeExample
WebElementNormal element interactionclick(), sendKeys()
getAttribute()Read attribute/propertygetAttribute("value")
ActionsAdvanced mouse and keyboard actionsmoveToElement()
JavascriptExecutorExecute JavaScript in browsersetAttribute()
CSS modificationChange visual propertiesstyle.outline

5. Basic Selenium Setup

import java.time.Duration;

import org.openqa.selenium.By;

import org.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

6. Starting WebDriver

WebDriver driver = new ChromeDriver();

driver.manage().window().maximize();

driver.get("https://example.com");

7. Locating a Web Element

WebElement username =

    driver.findElement(By.id("username"));

8. Common Selenium Locators

LocatorExample
IDBy.id("username")
NameBy.name("username")
Class NameBy.className("input-field")
Tag NameBy.tagName("input")
Link TextBy.linkText("Login")
Partial Link TextBy.partialLinkText("Log")
CSS SelectorBy.cssSelector("#username")
XPathBy.xpath("//input[@id='username']")

9. Modifying an Input with sendKeys()

For normal user-like text entry, Selenium's sendKeys() method should generally be preferred.

WebElement username =

    driver.findElement(By.id("username"));

 

username.sendKeys("admin");

10. Clearing an Input

username.clear();

username.sendKeys("newUser");

11. Modifying Input Value with JavaScript

JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

js.executeScript(

    "arguments[0].value='admin';",

    username

);

12. Understanding arguments[0]

arguments[0] represents the first object passed to executeScript(). When a WebElement is passed to JavaScript, Selenium exposes it to the script as the corresponding DOM element.

js.executeScript(

    "arguments[0].value='admin';",

    username

);

13. Modifying Multiple Elements

WebElement firstName =

    driver.findElement(By.id("firstName"));

 

WebElement lastName =

    driver.findElement(By.id("lastName"));

 

js.executeScript(

    "arguments[0].value='John';" +

    "arguments[1].value='Smith';",

    firstName,

    lastName

);

14. Modifying an HTML Attribute

The JavaScript setAttribute() method can change an HTML attribute.

js.executeScript(

    "arguments[0].setAttribute('value','admin');",

    username

);

15. Changing the ID Attribute

js.executeScript(

    "arguments[0].setAttribute('id','newUsername');",

    username

);

Changing an element's locator attributes during a test can make subsequent automation difficult to maintain, so this technique should normally be restricted to controlled scenarios.

16. Changing the Class Attribute

js.executeScript(

    "arguments[0].setAttribute('class','modified-input');",

    username

);

17. Adding a CSS Class

js.executeScript(

    "arguments[0].classList.add('selenium-highlight');",

    username

);

18. Removing a CSS Class

js.executeScript(

    "arguments[0].classList.remove('selenium-highlight');",

    username

);

19. Toggling a CSS Class

js.executeScript(

    "arguments[0].classList.toggle('active');",

    username

);

20. Checking Whether a Class Exists

Boolean result = (Boolean) js.executeScript(

    "return arguments[0].classList.contains('active');",

    username

);

 

System.out.println("Class exists: " + result);

21. Modifying CSS Properties

JavaScript can modify inline CSS properties through the element's style object.

js.executeScript(

    "arguments[0].style.backgroundColor='yellow';",

    username

);

22. Changing Text Color

js.executeScript(

    "arguments[0].style.color='red';",

    username

);

23. Changing Background Color

js.executeScript(

    "arguments[0].style.backgroundColor='lightblue';",

    username

);

24. Changing Font Size

js.executeScript(

    "arguments[0].style.fontSize='20px';",

    username

);

25. Changing Font Weight

js.executeScript(

    "arguments[0].style.fontWeight='bold';",

    username

);

26. Changing Border

js.executeScript(

    "arguments[0].style.border='3px solid red';",

    username

);

27. Changing Outline

Outline is particularly useful for temporary visual debugging because it generally does not affect the element's layout.

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    username

);

28. Adding Box Shadow

js.executeScript(

    "arguments[0].style.boxShadow='0 0 10px red';",

    username

);

29. Changing Width

js.executeScript(

    "arguments[0].style.width='300px';",

    username

);

30. Changing Height

js.executeScript(

    "arguments[0].style.height='50px';",

    username

);

31. Changing Visibility

js.executeScript(

    "arguments[0].style.visibility='visible';",

    username

);

32. Hiding an Element

js.executeScript(

    "arguments[0].style.display='none';",

    username

);

33. Showing a Hidden Element

js.executeScript(

    "arguments[0].style.display='block';",

    username

);

Changing visibility through JavaScript is useful for controlled investigation, but it does not necessarily represent how a real user would normally reach or interact with that element.

34. Removing the Disabled Attribute

WebElement button =

    driver.findElement(By.id("submit"));

 

js.executeScript(

    "arguments[0].removeAttribute('disabled');",

    button

);

35. Adding the Disabled Attribute

js.executeScript(

    "arguments[0].setAttribute('disabled','true');",

    button

);

36. Reading Attributes Before Modification

String value =

    username.getAttribute("value");

 

System.out.println(value);

37. Reading Class Attribute

String className =

    username.getAttribute("class");

 

System.out.println(className);

38. Reading ID Attribute

String id =

    username.getAttribute("id");

 

System.out.println(id);

39. Reading href Attribute

WebElement link =

    driver.findElement(By.tagName("a"));

 

String href =

    link.getAttribute("href");

 

System.out.println(href);

40. Modifying a Link href

js.executeScript(

    "arguments[0].setAttribute(" +

    "'href','https://example.com/profile');",

    link

);

41. Modifying Button Text

js.executeScript(

    "arguments[0].textContent='Submit Order';",

    button

);

42. Using innerText

js.executeScript(

    "arguments[0].innerText='Submit Order';",

    button

);

43. textContent vs innerText

PropertyDescription
textContentWorks with the text content of the DOM.
innerTextRepresents rendered text and is influenced by CSS visibility.

44. Modifying Placeholder

js.executeScript(

    "arguments[0].setAttribute(" +

    "'placeholder','Enter Username');",

    username

);

45. Removing Placeholder

js.executeScript(

    "arguments[0].removeAttribute('placeholder');",

    username

);

46. Modifying the name Attribute

js.executeScript(

    "arguments[0].setAttribute('name','userName');",

    username

);

47. Modifying the type Attribute

js.executeScript(

    "arguments[0].setAttribute('type','text');",

    username

);

48. Changing Password Input Type

WebElement password =

    driver.findElement(By.id("password"));

 

js.executeScript(

    "arguments[0].setAttribute('type','text');",

    password

);

This can expose password text visually and should only be used in a controlled test or debugging environment.

49. Attribute vs Property

AttributeProperty
Part of HTML markupCurrent state of the DOM object
Can be modified with setAttribute()Can be modified directly with JavaScript
Example: value attributeExample: input.value

50. Modifying the value Property

js.executeScript(

    "arguments[0].value='Test Data';",

    username

);

51. Modifying Checkbox State

WebElement checkbox =

    driver.findElement(By.id("terms"));

 

js.executeScript(

    "arguments[0].checked=true;",

    checkbox

);

52. Unchecking a Checkbox

js.executeScript(

    "arguments[0].checked=false;",

    checkbox

);

53. Checking Checkbox State

Boolean checked = (Boolean) js.executeScript(

    "return arguments[0].checked;",

    checkbox

);

 

System.out.println("Checked: " + checked);

54. Modifying Radio Button State

WebElement radio =

    driver.findElement(By.id("male"));

 

js.executeScript(

    "arguments[0].checked=true;",

    radio

);

55. Modifying a Select Element

For standard HTML select elements, Selenium's Select class should generally be preferred for normal user-like automation.

import org.openqa.selenium.support.ui.Select;

 

WebElement country =

    driver.findElement(By.id("country"));

 

Select select =

    new Select(country);

 

select.selectByVisibleText("India");

56. JavaScript Modification of Select Value

js.executeScript(

    "arguments[0].value='IN';",

    country

);

57. Dispatching a Change Event

Some applications listen for change events. Changing a DOM property alone may not trigger the application's event handlers.

js.executeScript(

    "arguments[0].value='IN';" +

    "arguments[0].dispatchEvent(" +

    "new Event('change',{bubbles:true})" +

    ");",

    country

);

58. Dispatching an Input Event

js.executeScript(

    "arguments[0].value='admin';" +

    "arguments[0].dispatchEvent(" +

    "new Event('input',{bubbles:true})" +

    ");",

    username

);

59. Why Events Matter

Modern applications may use JavaScript frameworks that listen for input, change, click, keyboard, or other browser events. Directly changing a DOM property does not always reproduce the complete sequence of events produced by a real user.

60. Modifying a Textarea

WebElement message =

    driver.findElement(By.id("message"));

 

js.executeScript(

    "arguments[0].value='Hello Selenium';",

    message

);

61. Modifying Email Input

WebElement email =

    driver.findElement(By.id("email"));

 

email.clear();

email.sendKeys("[email protected]");

62. Modifying an Image

WebElement image =

    driver.findElement(By.id("productImage"));

 

js.executeScript(

    "arguments[0].setAttribute(" +

    "'src','/images/test.png');",

    image

);

63. Modifying Image Size

js.executeScript(

    "arguments[0].style.width='200px';" +

    "arguments[0].style.height='200px';",

    image

);

64. Modifying Table Rows

WebElement row =

    driver.findElement(

        By.cssSelector("table tbody tr")

    );

 

js.executeScript(

    "arguments[0].style.backgroundColor='yellow';",

    row

);

65. Modifying Table Cells

WebElement cell =

    driver.findElement(

        By.cssSelector("table tbody tr td")

    );

 

js.executeScript(

    "arguments[0].style.fontWeight='bold';",

    cell

);

66. Modifying Multiple Web Elements

List<WebElement> elements =

    driver.findElements(

        By.cssSelector(".product")

    );

 

for (WebElement element : elements) {

    js.executeScript(

        "arguments[0].style.outline='2px solid red';",

        element

    );

}

67. Modifying Elements Using CSS Selector

WebElement element =

    driver.findElement(

        By.cssSelector(".login-button")

    );

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    element

);

68. Modifying Elements Using XPath

WebElement element =

    driver.findElement(

        By.xpath("//button[text()='Login']")

    );

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    element

);

69. Highlighting a Web Element

Highlighting is one of the most useful DOM modifications for debugging automation.

js.executeScript(

    "arguments[0].style.outline='4px solid red';",

    element

);

70. Creating a Highlight Utility

public static void highlight(

        WebDriver driver,

        WebElement element) {

 

    JavascriptExecutor js =

        (JavascriptExecutor) driver;

 

    js.executeScript(

        "arguments[0].style.outline='3px solid red';",

        element

    );

}

71. Modifying an Attribute with a Utility Method

public static void setAttribute(

        WebDriver driver,

        WebElement element,

        String attribute,

        String value) {

 

    JavascriptExecutor js =

        (JavascriptExecutor) driver;

 

    js.executeScript(

        "arguments[0].setAttribute(" +

        "arguments[1], arguments[2]);",

        element,

        attribute,

        value

    );

}

72. Using the Attribute Utility

setAttribute(

    driver,

    username,

    "placeholder",

    "Enter Username"

);

73. Removing an Attribute with a Utility

public static void removeAttribute(

        WebDriver driver,

        WebElement element,

        String attribute) {

 

    JavascriptExecutor js =

        (JavascriptExecutor) driver;

 

    js.executeScript(

        "arguments[0].removeAttribute(arguments[1]);",

        element,

        attribute

    );

}

74. Setting a CSS Property with a Utility

public static void setStyle(

        WebDriver driver,

        WebElement element,

        String property,

        String value) {

 

    JavascriptExecutor js =

        (JavascriptExecutor) driver;

 

    js.executeScript(

        "arguments[0].style[arguments[1]]=arguments[2];",

        element,

        property,

        value

    );

}

75. Using the CSS Utility

setStyle(

    driver,

    username,

    "backgroundColor",

    "yellow"

);

76. Restoring Original Style

String originalStyle =

    element.getAttribute("style");

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    element

);

 

// Debugging or screenshot operation

 

js.executeScript(

    "arguments[0].setAttribute('style', arguments[1]);",

    element,

    originalStyle

);

77. Modifying an Element Before Screenshot

js.executeScript(

    "arguments[0].style.outline='4px solid red';",

    element

);

 

File screenshot =

    ((TakesScreenshot) driver)

        .getScreenshotAs(OutputType.FILE);

78. Modify Web Element After Explicit Wait

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement element =

    wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            By.id("username")

        )

    );

 

highlight(driver, element);

79. Modifying Dynamic Web Elements

Dynamic elements may appear after page loading or may be re-rendered by the application. Always synchronize before interacting with them.

WebElement dynamicElement =

    wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            By.cssSelector(".dynamic-element")

        )

    );

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    dynamicElement

);

80. Handling Stale Web Elements

If the DOM is refreshed or re-rendered, a previously stored WebElement may become stale. Locate the current element again.

WebElement element =

    driver.findElement(By.id("username"));

 

driver.navigate().refresh();

 

element =

    driver.findElement(By.id("username"));

81. Modify Elements Inside an iframe

An iframe has its own browsing context. Selenium must switch into the frame before locating and modifying its elements.

WebElement frame =

    driver.findElement(By.id("paymentFrame"));

 

driver.switchTo().frame(frame);

 

WebElement payButton =

    driver.findElement(By.id("pay"));

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    payButton

);

 

driver.switchTo().defaultContent();

82. Modify Elements Inside a Modal

WebElement modalInput =

    driver.findElement(

        By.cssSelector(".modal input")

    );

 

js.executeScript(

    "arguments[0].style.backgroundColor='yellow';",

    modalInput

);

83. Modify Login Form Elements

WebElement username =

    driver.findElement(By.id("username"));

 

WebElement password =

    driver.findElement(By.id("password"));

 

username.clear();

username.sendKeys("admin");

 

password.clear();

password.sendKeys("Password123");

84. Modify Login Button Style

WebElement loginButton =

    driver.findElement(By.id("login"));

 

js.executeScript(

    "arguments[0].style.outline='3px solid green';",

    loginButton

);

85. Modify an E-Commerce Product Card

WebElement product =

    driver.findElement(

        By.cssSelector(".product-card")

    );

 

js.executeScript(

    "arguments[0].style.outline='3px solid blue';",

    product

);

86. Modify Checkout Form

WebElement address =

    driver.findElement(By.id("address"));

 

address.clear();

address.sendKeys("Mumbai, India");

87. Modify Navigation Link

WebElement home =

    driver.findElement(By.linkText("Home"));

 

js.executeScript(

    "arguments[0].style.color='red';",

    home

);

88. Modify Form Button Text

WebElement submit =

    driver.findElement(By.id("submit"));

 

js.executeScript(

    "arguments[0].textContent='Submit Form';",

    submit

);

89. Modify Web Elements with Page Object Model

When element modification is used across multiple test cases, it can be organized into reusable Page Object or utility methods. This helps keep test code maintainable.

public class LoginPage {

 

    private WebDriver driver;

 

    private By username =

        By.id("username");

 

    private By password =

        By.id("password");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public WebElement getUsername() {

        return driver.findElement(username);

    }

 

    public WebElement getPassword() {

        return driver.findElement(password);

    }

}

90. Using Page Object Elements

LoginPage loginPage =

    new LoginPage(driver);

 

WebElement username =

    loginPage.getUsername();

 

highlight(driver, username);

91. Complete Modification Utility Class

public class ModifyElementUtils {

 

    public static void highlight(

            WebDriver driver,

            WebElement element) {

 

        JavascriptExecutor js =

            (JavascriptExecutor) driver;

 

        js.executeScript(

            "arguments[0].style.outline='3px solid red';",

            element

        );

    }

 

    public static void setAttribute(

            WebDriver driver,

            WebElement element,

            String attribute,

            String value) {

 

        JavascriptExecutor js =

            (JavascriptExecutor) driver;

 

        js.executeScript(

            "arguments[0].setAttribute(" +

            "arguments[1], arguments[2]);",

            element,

            attribute,

            value

        );

    }

 

    public static void removeAttribute(

            WebDriver driver,

            WebElement element,

            String attribute) {

 

        JavascriptExecutor js =

            (JavascriptExecutor) driver;

 

        js.executeScript(

            "arguments[0].removeAttribute(arguments[1]);",

            element,

            attribute

        );

    }

 

    public static void setStyle(

            WebDriver driver,

            WebElement element,

            String property,

            String value) {

 

        JavascriptExecutor js =

            (JavascriptExecutor) driver;

 

        js.executeScript(

            "arguments[0].style[arguments[1]]=arguments[2];",

            element,

            property,

            value

        );

    }

}

92. Using the Complete Utility

ModifyElementUtils.highlight(

    driver,

    username

);

 

ModifyElementUtils.setAttribute(

    driver,

    username,

    "placeholder",

    "Enter Username"

);

 

ModifyElementUtils.setStyle(

    driver,

    username,

    "backgroundColor",

    "yellow"

);

93. Modify Web Elements and Perform Normal Selenium Action

Modification and interaction are separate concepts. For example, JavaScript can highlight an element while Selenium performs the actual click.

WebElement button =

    driver.findElement(By.id("submit"));

 

ModifyElementUtils.highlight(

    driver,

    button

);

 

button.click();

94. Selenium Click vs JavaScript Modification

RequirementRecommended Technique
Normal clickWebElement.click()
Enter textsendKeys()
Clear textclear()
Read attributegetAttribute()
Modify attributeJavaScript setAttribute()
Remove attributeJavaScript removeAttribute()
Modify CSSJavaScript style properties
Modify DOM texttextContent/innerText
Advanced mouse interactionActions class

95. Why Not Use JavaScript for Everything?

JavaScriptExecutor is powerful, but using it for every interaction can make tests less representative of normal user behavior. Selenium's standard WebDriver APIs should generally be preferred for regular browser interactions.

96. Common Mistake: Modifying Without Waiting

If the element has not appeared yet, modification may fail.

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement element =

    wait.until(

        ExpectedConditions.presenceOfElementLocated(

            By.id("username")

        )

    );

97. Common Mistake: Using an Old WebElement

After a page refresh or DOM re-render, a previously stored WebElement may become stale. Re-locate the element when necessary.

98. Common Mistake: Ignoring Application Events

Directly changing a DOM value does not necessarily trigger the events used by the application. When appropriate, dispatch the required event and verify the resulting application state.

99. Common Mistake: Bypassing Application Behavior

Removing disabled attributes or forcing hidden elements to become visible can bypass normal application behavior. Such techniques should only be used when they match the specific testing objective.

100. Common Mistake: Changing Locator Attributes

Changing an id, class, or name during automation can cause later locators to fail and can make test behavior difficult to understand.

101. Best Practice: Prefer WebDriver APIs

  • Use click() for normal clicks.
  • Use sendKeys() for normal keyboard input.
  • Use clear() for editable fields.
  • Use Select for standard HTML select controls.
  • Use Actions for advanced mouse and keyboard interactions.
  • Use JavaScriptExecutor for appropriate DOM-level tasks.

102. Best Practice: Use Explicit Waits

WebDriverWait wait =

    new WebDriverWait(driver, Duration.ofSeconds(10));

 

WebElement element =

    wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            By.id("username")

        )

    );

103. Best Practice: Verify Modification

js.executeScript(

    "arguments[0].setAttribute('data-status','updated');",

    element

);

 

String status =

    element.getAttribute("data-status");

 

System.out.println(

    "Status: " + status

);

104. Best Practice: Restore Temporary Changes

Temporary CSS or DOM changes should be restored when they are used only for debugging, visualization, or screenshots.

105. Best Practice: Create Reusable Utilities

If the same modification is needed across several tests, create reusable utility methods rather than repeating JavaScript throughout the test suite.

106. Best Practice: Keep JavaScript Small

Short JavaScript statements are easier to understand, debug, and maintain than large blocks of embedded JavaScript.

107. Practical Example: Login Page Modification

WebDriver driver = new ChromeDriver();

 

driver.manage().window().maximize();

driver.get("https://example.com/login");

 

JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

WebElement username =

    driver.findElement(By.id("username"));

 

WebElement password =

    driver.findElement(By.id("password"));

 

WebElement login =

    driver.findElement(By.id("login"));

 

username.clear();

username.sendKeys("admin");

 

password.clear();

password.sendKeys("Password123");

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    login

);

 

login.click();

108. Practical Example: Modify Multiple Form Fields

WebElement firstName =

    driver.findElement(By.id("firstName"));

 

WebElement email =

    driver.findElement(By.id("email"));

 

WebElement phone =

    driver.findElement(By.id("phone"));

 

firstName.clear();

firstName.sendKeys("John");

 

email.clear();

email.sendKeys("[email protected]");

 

phone.clear();

phone.sendKeys("9876543210");

109. Practical Example: Modify Button Text and Style

WebElement button =

    driver.findElement(By.id("submit"));

 

js.executeScript(

    "arguments[0].textContent='Submit Application';" +

    "arguments[0].style.backgroundColor='green';" +

    "arguments[0].style.color='white';",

    button

);

110. Practical Example: Modify All Input Fields

List<WebElement> inputs =

    driver.findElements(By.cssSelector("input"));

 

for (WebElement input : inputs) {

    js.executeScript(

        "arguments[0].style.outline='2px solid red';",

        input

    );

}

111. Practical Example: Modify Product Cards

List<WebElement> products =

    driver.findElements(

        By.cssSelector(".product-card")

    );

 

for (WebElement product : products) {

    js.executeScript(

        "arguments[0].style.boxShadow='0 0 10px red';",

        product

    );

}

112. Practical Example: Modify Table Rows

List<WebElement> rows =

    driver.findElements(

        By.cssSelector("table tbody tr")

    );

 

for (WebElement row : rows) {

    js.executeScript(

        "arguments[0].style.outline='2px solid blue';",

        row

    );

}

113. Practical Example: Checkbox State

WebElement terms =

    driver.findElement(By.id("terms"));

 

if (!terms.isSelected()) {

    terms.click();

}

 

System.out.println(

    "Selected: " + terms.isSelected()

);

114. Practical Example: Controlled JavaScript Checkbox Modification

js.executeScript(

    "arguments[0].checked=true;" +

    "arguments[0].dispatchEvent(" +

    "new Event('change',{bubbles:true})" +

    ");",

    terms

);

115. Practical Example: Modify Hidden Element for Debugging

WebElement hidden =

    driver.findElement(By.id("hiddenElement"));

 

js.executeScript(

    "arguments[0].style.display='block';",

    hidden

);

116. Practical Example: Remove Disabled State

WebElement submit =

    driver.findElement(By.id("submit"));

 

js.executeScript(

    "arguments[0].removeAttribute('disabled');",

    submit

);

117. Practical Example: Add Disabled State

js.executeScript(

    "arguments[0].setAttribute('disabled','true');",

    submit

);

118. Practical Example: Modify Link URL

WebElement profile =

    driver.findElement(By.id("profile"));

 

js.executeScript(

    "arguments[0].setAttribute(" +

    "'href','https://example.com/profile');",

    profile

);

119. Practical Example: Modify Image Source

WebElement logo =

    driver.findElement(By.id("logo"));

 

js.executeScript(

    "arguments[0].setAttribute(" +

    "'src','/images/test-logo.png');",

    logo

);

120. Practical Example: Modify Element Text

WebElement message =

    driver.findElement(By.id("message"));

 

js.executeScript(

    "arguments[0].textContent='Test completed successfully';",

    message

);

121. Practical Example: Add CSS Class

js.executeScript(

    "arguments[0].classList.add('test-highlight');",

    message

);

122. Practical Example: Remove CSS Class

js.executeScript(

    "arguments[0].classList.remove('test-highlight');",

    message

);

123. Practical Example: Modify Attribute and Verify

js.executeScript(

    "arguments[0].setAttribute('data-test','passed');",

    element

);

 

String result =

    element.getAttribute("data-test");

 

if ("passed".equals(result)) {

    System.out.println(

        "Modification successful"

    );

}

124. Modify Web Elements in TestNG

import org.testng.annotations.Test;

 

public class ModifyElementTest {

 

    @Test

    public void modifyElementTest() {

 

        WebElement username =

            driver.findElement(By.id("username"));

 

        JavascriptExecutor js =

            (JavascriptExecutor) driver;

 

        js.executeScript(

            "arguments[0].style.outline='3px solid red';",

            username

        );

 

        username.clear();

        username.sendKeys("admin");

 

        System.out.println(

            username.getAttribute("value")

        );

    }

}

125. Modify Web Element Flow

Start

  |

  v

Open Browser

  |

  v

Open Application

  |

  v

Locate Web Element

  |

  v

Wait for Required State

  |

  v

Choose Modification

  |

  +----> WebElement API

  |

  +----> JavaScriptExecutor

  |

  +----> Actions API

  |

  v

Modify Element

  |

  v

Verify Result

  |

  v

Continue Test

  |

  v

End

126. Web Element Modification Decision Guide

RequirementRecommended Approach
Enter textsendKeys()
Clear textclear()
Click elementclick()
Read attributegetAttribute()
Modify HTML attributeJavaScript setAttribute()
Remove attributeJavaScript removeAttribute()
Change CSSJavaScript style property
Change DOM texttextContent/innerText
Advanced mouse actionActions class
Debug/highlightJavaScriptExecutor

127. Common Selenium Exceptions

ExceptionPossible Reason
NoSuchElementExceptionElement cannot be located.
StaleElementReferenceExceptionDOM changed after the element was located.
ElementNotInteractableExceptionElement cannot be interacted with normally.
ElementClickInterceptedExceptionAnother element blocks the click.
TimeoutExceptionExpected condition was not met in time.

128. Debugging Modification Failures

  1. Verify the locator.
  2. Check whether the element exists.
  3. Check page loading state.
  4. Check whether the element is inside an iframe.
  5. Check whether an overlay or modal is blocking it.
  6. Check for DOM re-rendering.
  7. Re-locate stale elements.
  8. Use explicit waits.
  9. Inspect the element using browser developer tools.
  10. Verify the modified value or attribute.

129. Interview Question: What is Modify Web Elements?

Modify Web Elements means changing or controlling attributes, properties, styles, text, or state of web elements during automation. Selenium's WebElement API is normally used for standard interactions, while JavaScriptExecutor can perform appropriate DOM-level modifications.

130. Interview Question: Can Selenium Modify HTML Attributes?

JavaScriptExecutor can directly modify HTML attributes using JavaScript methods such as setAttribute() and removeAttribute().

131. Interview Question: How Do You Modify an Attribute?

js.executeScript(

    "arguments[0].setAttribute('data-status','updated');",

    element

);

132. Interview Question: How Do You Change CSS?

js.executeScript(

    "arguments[0].style.backgroundColor='yellow';",

    element

);

133. Interview Question: How Do You Modify Text?

js.executeScript(

    "arguments[0].textContent='Updated Text';",

    element

);

134. Interview Question: What is arguments[0]?

arguments[0] is the first parameter supplied to executeScript(). When a WebElement is passed, it represents that element's corresponding DOM object inside the JavaScript execution context.

135. Interview Question: Can JavaScript Remove Disabled State?

Yes. JavaScript can remove a disabled attribute, but this can bypass the application's intended state. It should only be used when that behavior is part of the specific test objective.

136. Interview Question: Does JavaScript Value Modification Trigger Events?

Not necessarily. Direct DOM property modification may not reproduce the events generated by normal user interaction. An appropriate event can be dispatched when the test specifically requires it.

137. Interview Question: Should JavaScriptExecutor Replace Selenium Methods?

No. Selenium's standard APIs should generally be preferred for normal browser interactions. JavaScriptExecutor should be used for suitable DOM-level operations, debugging, or controlled specialized scenarios.

138. Interview Question: How Do You Highlight an Element?

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    element

);

139. Interview Question: How Do You Remove an Attribute?

js.executeScript(

    "arguments[0].removeAttribute('disabled');",

    element

);

140. Interview Question: How Do You Modify Multiple Elements?

List<WebElement> elements =

    driver.findElements(

        By.cssSelector(".item")

    );

 

for (WebElement element : elements) {

    js.executeScript(

        "arguments[0].style.outline='2px solid red';",

        element

    );

}

141. Quick Revision Table

ConceptKey Point
WebElementRepresents an HTML element.
sendKeys()Enters keyboard input.
clear()Clears editable fields.
getAttribute()Reads an attribute or property value.
setAttribute()Modifies an HTML attribute.
removeAttribute()Removes an HTML attribute.
styleModifies CSS properties.
classListAdds, removes, or toggles CSS classes.
textContentReads or modifies DOM text.
JavascriptExecutorExecutes JavaScript in the browser context.
Explicit WaitSynchronizes automation with dynamic elements.
POMOrganizes reusable page element logic.

142. Best Practices Checklist

  • Use stable locators.
  • Prefer normal Selenium methods for normal user interactions.
  • Use JavaScriptExecutor only when appropriate.
  • Use explicit waits for dynamic elements.
  • Re-locate elements after DOM refreshes or re-rendering.
  • Verify important modifications.
  • Consider application-specific events when changing DOM properties.
  • Keep JavaScript readable and focused.
  • Create reusable utility methods.
  • Restore temporary changes when necessary.
  • Use controlled test environments.
  • Do not use DOM modification to hide actual application defects.

143. Practical Mini Project: Web Element Modification Test Suite

A practical Selenium project can combine login automation, form modification, attribute verification, CSS highlighting, checkbox state validation, dynamic elements, and debugging.

Login Page

   |

   v

Locate Username

   |

   v

Enter Username

   |

   v

Locate Password

   |

   v

Enter Password

   |

   v

Highlight Login Button

   |

   v

Verify Element

   |

   v

Click Login

   |

   v

Verify Dashboard

   |

   v

End Test

144. Complete Practical Example

WebDriver driver = new ChromeDriver();

 

driver.manage().window().maximize();

 

driver.get("https://example.com");

 

JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

WebElement username =

    driver.findElement(By.id("username"));

 

WebElement login =

    driver.findElement(By.id("login"));

 

username.clear();

username.sendKeys("admin");

 

js.executeScript(

    "arguments[0].setAttribute(" +

    "'data-test-status','prepared');",

    username

);

 

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    login

);

 

String status =

    username.getAttribute("data-test-status");

 

System.out.println(

    "Status: " + status

);

 

login.click();

 

driver.quit();

145. Conclusion

Modify Web Elements is an important Selenium WebDriver concept for understanding how automated tests can inspect and change elements in the browser DOM. Selenium's WebElement methods should normally be used for standard interactions such as typing, clicking, clearing fields, and selecting controls.

JavaScriptExecutor provides additional capabilities for controlled DOM operations such as changing attributes, CSS styles, text, classes, and certain element properties. The most reliable automation approach combines stable locators, appropriate waits, normal Selenium interactions, reusable utilities, and verification of the resulting application state.


146. Selenium Training Resources

JustAcademy's Selenium training curriculum includes Selenium WebDriver, locating elements, browser automation, forms, buttons, dropdowns, WebElements, advanced interactions, waits, dynamic elements, TestNG, Page Object Model, automation frameworks, reporting, debugging, and practical automation projects.

Selenium Training Course

Register for Course Demo

147. Final Quick Reference

// Locate

WebElement element =

    driver.findElement(By.id("username"));

 

// Enter value

element.clear();

element.sendKeys("Admin");

 

// Read attribute

String value =

    element.getAttribute("value");

 

// JavaScript

JavascriptExecutor js =

    (JavascriptExecutor) driver;

 

// Modify attribute

js.executeScript(

    "arguments[0].setAttribute('data-status','updated');",

    element

);

 

// Remove attribute

js.executeScript(

    "arguments[0].removeAttribute('disabled');",

    element

);

 

// Modify CSS

js.executeScript(

    "arguments[0].style.outline='3px solid red';",

    element

);

 

// Modify text

js.executeScript(

    "arguments[0].textContent='Updated';",

    element

);

 

// Add class

js.executeScript(

    "arguments[0].classList.add('active');",

    element

);

 

// Remove class

js.executeScript(

    "arguments[0].classList.remove('active');",

    element

);

whatsapp